/**
 *  Copyright 2010 ShenYang voole Co. Ltd.
 *  All right reserved. 
 */
package cn.piaoyi.dao.hibernate;


import java.sql.SQLException;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import cn.piaoyi.bean.Cart;
import cn.piaoyi.comm.Constant;
import cn.piaoyi.dao.CartDAO;

/**
 * 功能描述:价格操作实现
 *
 * 创建日期 Apr 10, 2010
 *
 * @author zhangbaochao
 *
 * @version 1.0
 *
 */
public class CartHibernateDAO extends HibernateDaoSupport implements CartDAO {

	private static final String LOAD_BY_ID = "from Cart where id = ?";
	private static final String  REMOVE_BY_ID = "delete from Cart where id = ?";
	private static final String  REMOVE_IN_IDS = "delete from Cart where id in (:ids)";
	private static final String  REMOVE_BY_UID = "delete from Cart where userId = ?";
	private static final String  REMOVE_ALL = "delete from Cart";
	private static final String  LOAD_BY_UID_PIC = "from Cart where userId = ? and priceId=?";
	
	/**
	 * 保存Cart对象
	 * 
	 * @param price
	 * 			Cart对象
	 * @return Cart
	 * 			Cart对象
	 */
	public Cart saveCart(Cart cart){
		this.getHibernateTemplate().save(cart);
		return cart;
	}
	/**
	 * 保存或更新Cart对象
	 * 
	 * @param cart
	 * 			Cart对象
	 * @return Cart
	 * 			Cart对象
	 */
	public Cart saveOrUpdateCart(Cart cart){
		this.getHibernateTemplate().saveOrUpdate(cart);
		return cart;
	}
	/**
	 * 保存Cart对象
	 * 
	 * @param cart
	 * 			Cart对象
	 * @return Cart
	 * 			Cart对象
	 */
	public Cart updateCart(Cart cart){
		this.getHibernateTemplate().update(cart);
		return cart;
	}
	
	/**
	 * 根据主键ID获取Cart对象
	 * 
	 * @param id
	 * 			主键ID
	 * @return Cart
	 * 			Cart对象
	 */
	public Cart findCartById(long id){
		List l = this.getHibernateTemplate().find(LOAD_BY_ID,id);
		if(l == null || l.isEmpty()){
			return null;
		}else{
			return (Cart) l.get(0);
		}
	}
	
	/**
	 * 根据UID PID获取Cart对象
	 * @param uid
	 * 			long
	 * @param pid
	 * 			long
	 * @return Cart
	 */
	public Cart findCartByUidPid(long uid,long pid){
		Object[] o = {new Long(uid),new Long(pid)};
		List l = this.getHibernateTemplate().find(LOAD_BY_UID_PIC,o);
		if(l == null || l.isEmpty()){
			return null;
		}else{
			return (Cart) l.get(0);
		}
	}
	/**
	 * 获取Cart个数
	 * 
	 * @param userId
	 * 			long
	 * @return int
	 * 			Cart个数
	 */
	public long getCartNum(final long userId){
		List l = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session s) throws HibernateException {
				Criteria c = s.createCriteria(Cart.class);
				c.setProjection(Projections.count("id"));
				if (userId != -1) {
					c.add(Restrictions.eq("userId", new Long(userId)));
				}
				return c.list();
			}
		});
		if (l == null || l.isEmpty()) {
			return 0;
		} else {
			return ((Integer) l.get(0)).longValue();
		}
	}
	
	/**
	 * 获取Price列表
	 * 
	 * @param userId
	 * 			long
	 * @param orderby
	 *            String
	 * @param ascOrDesc
	 *            int
	 * @param firstResult
	 *            int
	 * @param maxResults
	 *            int
	 * @return List
	 * 			Cart对象列表
	 */
	public List findPrices(final long userId,final String orderby, final int ascOrDesc, final int firstResult, final int maxResults){
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session s) throws HibernateException {
				Criteria c = s.createCriteria(Cart.class);
				if (userId != -1) {
					c.add(Restrictions.eq("userId", new Long(userId)));
				}
				if (StringUtils.isNotBlank(orderby)) {
					if (ascOrDesc == Constant.ORDER_ASC) {
						c.addOrder(Order.asc(orderby));
					}
					if (ascOrDesc == Constant.ORDER_DESC) {
						c.addOrder(Order.desc(orderby));
					}
				}
				c.setFirstResult(firstResult);
				c.setMaxResults(maxResults);
				return c.list();
			}
		});
	}
	
	/**
	 * 获取Cart列表
	 * 
	 * @param userId
	 * 			long
	 * @param orderby
	 *            String
	 * @param ascOrDesc
	 *            int
	 * @return List
	 * 			Cart对象列表
	 */
	public List findPrices(final long userId,final String orderby, final int ascOrDesc){
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session s) throws HibernateException {
				Criteria c = s.createCriteria(Cart.class);
				if (userId != -1) {
					c.add(Restrictions.eq("userId", new Long(userId)));
				}
				if (StringUtils.isNotBlank(orderby)) {
					if (ascOrDesc == Constant.ORDER_ASC) {
						c.addOrder(Order.asc(orderby));
					}
					if (ascOrDesc == Constant.ORDER_DESC) {
						c.addOrder(Order.desc(orderby));
					}
				}
				return c.list();
			}
		});
	}
	
	/**
	 * 删除Cart对象
	 */
	public void removeCartById(final long id){
	    getHibernateTemplate().execute(new HibernateCallback() {
	        public Object doInHibernate(Session s) throws HibernateException, SQLException {
	          Query query = s.createQuery(REMOVE_BY_ID);
	          query.setLong(0, id);
	          query.executeUpdate();
	          return null;
	        }
	      });
	}
	
	public void removeCartInIds(final List ids){
		getHibernateTemplate().execute(new HibernateCallback() {
		      public Object doInHibernate(Session s) throws HibernateException, SQLException {
		        Query query = s.createQuery(REMOVE_IN_IDS);
		        query.setParameterList("ids", ids);
		        query.executeUpdate();
		         return null;
		      }
		    });
	}
	
	public void removeCartByUid(final long userId){
		getHibernateTemplate().execute(new HibernateCallback() {
	        public Object doInHibernate(Session s) throws HibernateException, SQLException {
	          Query query = s.createQuery(REMOVE_BY_UID);
	          query.setLong(0, userId);
	          query.executeUpdate();
	          return null;
	        }
	      });
	}
	
	public void removeCartAll(){
		getHibernateTemplate().execute(new HibernateCallback() {
	        public Object doInHibernate(Session s) throws HibernateException, SQLException {
	          Query query = s.createQuery(REMOVE_ALL);
	          query.executeUpdate();
	          return null;
	        }
	      });
	}
}
